//
//  HMVistorViewController.swift
//  SecondWB
//
//  Created by 赖建伟 on 16/11/27.
//  Copyright © 2016年 Itheima. All rights reserved.
//

import UIKit

class HMVistorViewController: UIViewController ,UIWebViewDelegate{
    
    var webView = UIWebView()
    
    override func loadView() {
        
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.green
        // Do any additional setup after loading the view.
        
        setNavigationBarMessage()
        loadWebView()
    }

    private func setNavigationBarMessage() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(back))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "autoFill", style: UIBarButtonItemStyle.plain, target: self, action: #selector(autoFill))
        
    }
    
    @objc private func back() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFill() {
        
        let jsString = "document.getElementById('userId').value='18998107347';document.getElementById('passwd').value='ljw7347'"
        
        webView.stringByEvaluatingJavaScript(from:jsString)
        
    }
    
    private func loadWebView() {
        /*
         App Key：
         1545363033
         App Secret：
         f5b1ba2d511a1eb4f6a0cb95bbd2c6a8
         http://www.baidu.com
         */
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=1545363033&redirect_uri=http://www.baidu.com"
        let url = URL.init(string: urlString)
        let request = URLRequest.init(url: url!)
        
        webView.loadRequest(request)
        
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request.url?.absoluteString)
        //Optional("http://www.baidu.com/?code=0e75f43188e489ac3a4c93a45dc3170e")
        
        if let urlString = request.url?.absoluteString {
            if (urlString.hasPrefix("http://www.baidu.com/")) {
                
//              print(request.url?.query)
                if let query = request.url?.query  {
                    
                    let code = query.substring(from: "code=".endIndex)
                    print(code)//8da81f4107ec5b244990e8d2be45849d
                    loadToken(code: code)
                }
                
                
            }
        }
        
        
        
        return true
    }
    
    
    private func loadToken(code: String) {
        
        let urlString: String = "https://api.weibo.com/oauth2/access_token"
        /* 	必选	类型及范围	说明
         client_id	true	string	申请应用时分配的AppKey。
         client_secret	true	string	申请应用时分配的AppSecret。
         grant_type	true	string	请求的类型，填写authorization_code
         
         grant_type为authorization_code时
         必选	类型及范围	说明
         code	true	string	调用authorize获得的code值。
         redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
         */
        let para:[String:Any] = [
            "client_id":AppKey,
            "client_secret": AppSecret,
            "code":code,
            "redirect_uri":AppURL
        ];
        
        HMHTTPClient.request(type: .post, classUrlString: urlString, parameters: para, success: {(json:[String : Any]) -> Void in
            
           let tokenModel = HMLoginToken(dict: json)
            
            print(tokenModel)
            
        }, failure: {(error:Error) -> Void in
            print(error)
        })
        
    }
    
    
    
}
